<template>
  <a-modal
    :title="title"
    @close="close"
    :maskClosable="false"
    width="800px"
    :footer="null"
    :closable="false"
    :visible="state.visible"
    :body-style="{ paddingBottom: '80px' }"
  >
    <div class="notify-wrap">
      <a-tabs v-model:activeKey="activeKey" @change="changeType">
        <a-tab-pane
          :key="item.type"
          :tab="item.typeName"
          v-for="item in menuList"
        >
        </a-tab-pane>
      </a-tabs>
      <div class="history-btn">
        <!-- <a-popover
          placement="bottom"
          :visible="showPopover"
          @visibleChange="handleHoverChange"
        >
          <template #content>
            <div class="pdd-history">
              <a-timeline
                style="
                  max-height: 400px;
                  overflow: auto;
                  padding-top: 10px;
                  max-width: 300px;
                "
              >
                <a-timeline-item
                  :color="item.completeState === 0 ? 'green' : 'grey'"
                  v-for="(item, index) in historyList"
                  :key="item.id"
                >
                  <div class="cp pr item">
                    <div>
                      <strong>{{ item.nodeCodeName }}</strong>
                      <div v-if="index !== 0">
                        处理人:{{ item.handlerName }}
                      </div>
                      <div>
                        {{ index === 0 ? '操作时间' : '开始时间' }}:{{
                          item.initiationTimeStr
                        }}
                      </div>
                      <div v-if="item.completeTimeStr && index !== 0">
                        结束时间:{{ item.completeTimeStr }}
                      </div>
                      <div v-if="index !== 0">耗时：{{ item.duration }}</div>
                    </div>
                    <div class="hidden-option">
                      <div class="column">
                        <div>
                          <a-button
                            @click="
                              (showPopover = false), $refs.edit.open(item, true)
                            "
                          >
                            编辑当前节点
                          </a-button>
                        </div>
                        <div
                          class="mt10"
                          v-if="
                            item.isCurrentHandler && item.completeState === 1
                          "
                        >
                          <a-button @click="complete"> 完结当前节点 </a-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </a-timeline-item>
              </a-timeline>
            </div>
          </template>
          <template #title>
            <span>历史</span>
          </template> -->
        <a-button
          type="primary"
          size="small"
          @click="historyRef.open(cp, true)"
        >
          历史
        </a-button>
        <!-- </a-popover> -->
      </div>
      <a-form
        ref="forms"
        :model="model"
        :rules="
          model.nextNodeCode === '999' ||
          model.nextNodeCode === '1000' ||
          model.nextNodeCode === '1001'
            ? endRules
            : rules
        "
        layout="vertical"
      >
        <a-row :gutter="10">
          <a-col :span="12">
            <a-form-item :label="'当前任务节点'" name="currentNodeCode">
              <a-select
                show-search
                placeholder="请选择"
                :option-filter-prop="children"
                :filter-option="filterOption"
                @change="changeCurrentNode"
                style="width: 100%"
                v-model:value="model.currentNodeCode"
              >
                <a-select-option
                  v-for="item in list"
                  :key="item.nodeCode"
                  :value="item.nodeCode"
                >
                  {{ item.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="'处理人'" name="currentHandler">
              <a-select
                show-search
                :option-filter-prop="children"
                :filter-option="filterOption"
                placeholder="请选择"
                style="width: 100%"
                v-model:value="model.currentHandler"
              >
                <a-select-option
                  v-for="item in staffList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="'下个任务节点'" name="nextNodeCode">
              <a-select
                show-search
                @change="changeNextNode"
                placeholder="请选择"
                :option-filter-prop="children"
                :filter-option="filterOption"
                style="width: 100%"
                v-model:value="model.nextNodeCode"
              >
                <a-select-option
                  v-for="item in list"
                  :key="item.nodeCode"
                  :value="item.nodeCode"
                >
                  {{ item.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="'下节点处理人'" name="handler">
              <a-select
                show-search
                :option-filter-prop="children"
                :filter-option="filterOption"
                @change="changeHandler"
                placeholder="请选择"
                style="width: 100%"
                v-model:value="model.handler"
              >
                <a-select-option
                  v-for="item in staffList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-row>
              <a-col :span="12">
                <div class="pr h30 mb20">
                  <h4>
                    <strong style="position: absolute; bottom: 12px"
                      >开始时间:{{ model.initiationTime }}</strong
                    >
                  </h4>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="pr h30 mb20">
                  <h4>
                    <strong style="position: absolute; bottom: 12px"
                      >时长:{{ model.duration }}</strong
                    >
                  </h4>
                </div>
              </a-col>
            </a-row>
          </a-col>

          <a-col :span="24">
            <a-row>
              <a-col :span="23">
                <a-form-item name="initiator">
                  <div class="df mr10">
                    <span class="mr10">发送留言：</span>
                    <a-switch v-model:checked="model.initiator" />
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="24">
            <a-row>
              <a-col :span="24">
                <a-form-item
                  :label="''"
                  name="defaultMessage"
                  :wrapper-col="{ span: 24 }"
                >
                  <a-textarea
                    placeholder="请输入"
                    :rows="4"
                    v-model:value="model.defaultMessage"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div
      :style="{
        position: 'absolute',
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e8e8e8',
        padding: '10px 16px',
        textAlign: 'right',
        left: 0,
        background: '#fff',
        borderRadius: '0 0 4px 4px'
      }"
    >
      <a-button style="margin-right: 8px" size="small" @click="close"
        >取消</a-button
      >
      <a-button type="primary" size="small" @click="onSubmit">保存</a-button>
    </div>
    <history ref="historyRef" />
    <edit ref="edit" @complete="getHistory(cp)" />
  </a-modal>
</template>

<script>
import form from '@/components/cupshe/mixin/form.js'
import { debounce } from 'lodash'
import { reactive, ref, toRefs } from 'vue'
import History from './history.vue'
import Edit from './edit.vue'
import {
  work_bench_get_node_config_post,
  work_bench_get_process_config_post,
  work_bench_node_process_manual_post,
  work_bench_list_history_post,
  work_bench_process_end_post,
  work_bench_node_cp_count_post
} from '@/server/modules/12142'
import { config_list_staff_post } from '@/server/modules/1890'
import { work_bench_get_handler } from '@/server/modules/pdd'
export default {
  name: 'addColor',
  mixins: [form],
  components: {
    History,
    Edit
  },
  data() {
    return {
      title: '任务',
      forms: ref(null),

      width: 900,
      cp: '',
      activeKey: 1,
      showPopover: false,
      defaultMessage: '',
      list: [],
      type: 0,
      menuList: [],
      historyList: [],
      formItemLayout: {
        labelCol: { span: 12 },
        wrapperCol: { span: 12 }
      },
      staffList: []
    }
  },
  //   created() {
  //     this.initMap()
  //   },
  methods: {
    // beforeOpen(data) {
    // },
    afterClose() {
      // console.log(this.formState)
    },
    changeHandler(option, value) {
      this.model = {
        ...this.model,
        defaultMessage: this.defaultMessage + '@' + value.children[0].children
      }
    },
    handleHoverChange(visible) {
      this.showPopover = visible
    },
    filterOption(input, option) {
      return (
        option.children[0].children
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    complete() {
      work_bench_process_end_post({ cp: this.cp }).then(
        ({ success, retInfo }) => {
          if (success) {
            this.getHistory(this.cp)
            this.$notification.success({
              message: '完结成功'
            })
            this.showPopover = false
          } else {
            this.$notification.error({
              message: retInfo || '完结失败'
            })
          }
        }
      )
    },
    changeCurrentNode(option) {
      work_bench_get_handler({
        cp: this.cp,
        nextNode: this.model.nextNodeCode,
        currentNode: option
      }).then(({ success, data, retInfo }) => {
        if (success) {
          this.defaultMessage = data.message
          // const nextNode = this.list.filter((f) => f.nodeCode === option)
          // if (nextNode.length) {
          // this.defaultMessage = nextNode[0].defaultCompleteMessage
          const handler = this.model.handler
          if (handler) {
            const current = this.staffList.filter(f => f.id === handler)
            if (current.length) {
              this.model = {
                ...this.model,
                defaultMessage: this.defaultMessage + '@' + current[0].name
              }
            }
          } else {
            this.model = {
              ...this.model,
              defaultMessage: this.defaultMessage
            }
          }

          // }
        } else {
          this.$notification.error({
            message: retInfo
          })
        }
      })
    },
    changeType(option) {
      this.activeKey = option
      this.getDetail(this.activeKey, this.cp)
    },
    changeNextNode(option) {
      work_bench_get_handler({
        cp: this.cp,
        nextNode: option,
        currentNode: this.model.currentNodeCode
      }).then(({ success, data, retInfo }) => {
        if (success) {
          this.defaultMessage = data.message
          this.model.handler = data.nextHandler
          const nextNode = this.list.filter(f => f.nodeCode === option)
          if (nextNode.length) {
            // this.defaultMessage = nextNode[0].defaultCompleteMessage
            if (this.model.handler) {
              const current = this.staffList.filter(
                f => f.id === this.model.handler
              )
              if (current.length) {
                this.model = {
                  ...this.model,
                  defaultMessage: this.defaultMessage + '@' + current[0].name
                }
              }
            } else {
              this.model = {
                ...this.model,
                defaultMessage: this.defaultMessage
              }
            }
          }
        } else {
          this.$message.error(retInfo)
        }
      })
    },
    async afterOpen({ cp, type }) {
      this.cp = cp
      this.type = type
      this.getHistory(cp)
      work_bench_node_cp_count_post({ nodeType: 1, cp }).then(
        async ({ success, data }) => {
          if (success) {
            this.menuList = data
            const tmp = data.filter(f => f.inProgress === 1)
            if (tmp.length) {
              this.activeKey = tmp[0].type
            } else {
              this.activeKey = data[0].type
            }
            if (type) {
              this.activeKey = type
            }
            this.getDetail(this.activeKey, this.cp)
          }
        }
      )
    },

    async getDetail(type, cp) {
      const { success, data, retInfo } = await work_bench_get_node_config_post({
        cp,
        type
      })
      if (success) {
        this.model = {
          ...data,
          type,
          initiator: true
        }
        this.defaultMessage = data.defaultMessage
        config_list_staff_post({}).then(({ success, data }) => {
          if (success) {
            this.staffList = data.list
            const staff = this.staffList.filter(
              f => f.id === this.model.handler
            )
            if (staff.length) {
              this.model.defaultMessage += '@' + staff[0].name
            }
          }
        })
        work_bench_get_process_config_post({
          proofFlowType: data.proofFlowType,
          cp: cp,
          currentNode: data.currentNodeCode,
          type
        }).then(({ success, data }) => {
          if (success) {
            this.list = data
          }
        })
      } else {
        this.$message.error(retInfo)
        this.close()
      }
    },
    getHistory(cp) {
      work_bench_list_history_post({ cps: [cp] }).then(({ success, data }) => {
        if (success) {
          this.historyList = data
        }
      })
    },
    async addRequest(values) {
      return this.updateRequest(values)
    },
    async updateRequest(values) {
      const {
        handler,
        currentHandler,
        currentNodeCode,
        defaultMessage,
        initiator,
        nextNodeCode
      } = values

      const { proofFlowType } = this.model
      const { cp } = this
      const data = {
        cp,
        currentHandler,
        handler,
        currentNode: currentNodeCode,
        message: defaultMessage,
        nextNode: nextNodeCode,
        proofFlowType,
        sendMessage: initiator ? 1 : 0
      }
      return work_bench_node_process_manual_post(data)
    }
  },
  setup() {
    const rules = {
      currentNodeCode: [
        {
          required: true,
          message: '请选择当前任务点'
        }
      ],
      currentHandler: [
        {
          required: true,
          message: '请选择处理人'
        }
      ],
      nextNodeCode: [
        {
          required: true,
          message: '请选择下一任务点'
        }
      ],
      defaultMessage: [
        {
          required: true,
          message: '请填写理由'
        }
      ],
      handler: [
        {
          required: true,
          message: '请选择下节点处理人'
        }
      ]
    }
    const endRules = {
      currentNodeCode: [
        {
          required: true,
          message: '请选择当前任务点'
        }
      ],
      currentHandler: [
        {
          required: true,
          message: '请选择处理人'
        }
      ],
      nextNodeCode: [
        {
          required: true,
          message: '请选择下一任务点'
        }
      ],
      defaultMessage: [
        {
          required: true,
          message: '请填写理由'
        }
      ],
      handler: [
        {
          required: false,
          message: '请选择下节点处理人'
        }
      ]
    }
    const historyRef = ref(null)
    const state = reactive({
      historyRef
    })
    return {
      rules,
      debounce,
      endRules,
      ...toRefs(state)
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .cooperation-item .ant-form-item {
  margin-bottom: 0 !important;
}
.pdd-history {
  .title {
    font-size: 20px;
    font-weight: bold;
    color: black;
  }
  .history-btn {
    position: absolute;
    top: 15px;
    right: 60px;
  }
  .item {
    min-height: 80px;
    max-width: 240px;
  }

  .hidden-option {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background: rgba(0, 0, 0, 0.5);
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
  }

  .hidden-option:hover {
    opacity: 1;
  }
}
.notify-wrap {
  .history-btn {
    position: absolute;
    top: 15px;
    right: 20px;
  }
  .title {
    color: rgba(0, 0, 0, 0.85);
    font-family: PingFang SC;
    font-size: 16px;
    font-style: normal;
    font-weight: 600;
    line-height: 22px;
    margin-left: 8px;
  }
  .close-icon {
    cursor: pointer;
  }
}
</style>
